﻿using MediatR;
using SY.BasicData.Api.Write.Basic.Applications.Cultivation.Command;
using SY.BasicData.Domain.Cultivation;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;

namespace SY.BasicData.Api.Write.Basic.Applications.Cultivation.CommandHandler
{
    public class AddImmunityCommandHandler : IRequestHandler<AddImmunityCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ImmunityModel> baseRepository;

        public AddImmunityCommandHandler(IBaseRepository<ImmunityModel> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public async Task<ApiResult<int>> Handle(AddImmunityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "免疫信息添加";
            
            // 确保 Id 为 0，让数据库自动生成
            foreach (var immunityModel in request.immunityModels)
            {
                immunityModel.Id = 0; // 确保 Id 为 0，让数据库自动生成
                immunityModel.IsDeleted = false; // 设置默认值
            }
            
            var model = await baseRepository.AddRange(request.immunityModels);
            result.Data = model;
            result.Code = model > 0 ? ApiEnum.Success : ApiEnum.Fail;
            result.Message = model > 0 ? "添加免疫信息成功" : "添加免疫信息失败";
            return await Task.FromResult(result);
        }
    }
}
